package com.yoda.youdianda.controller;

import cn.hutool.crypto.SecureUtil;
import com.yoda.youdianda.common.ErrorResult;
import com.yoda.youdianda.common.R;
import com.yoda.youdianda.domain.SysUser;
import com.yoda.youdianda.domain.YddUser;
import com.yoda.youdianda.dto.SysUserDto;
import com.yoda.youdianda.dto.UserLoginFrontDto;
import com.yoda.youdianda.exception.BusinessException;
import com.yoda.youdianda.service.SystemUserService;
import com.yoda.youdianda.service.YddUserService;
import com.yoda.youdianda.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/home/index")
public class IndexController {
    @Autowired
    private YddUserService yddUserService;

    @PostMapping("/login")
    public R frontLogin(@RequestBody UserLoginFrontDto userDto) {
        if (Objects.isNull(userDto.getMobile()) || Objects.isNull(userDto.getPassword())) {
            throw new BusinessException(ErrorResult.nullError());
        }
        YddUser yddUser = yddUserService.selectUserByPhone(userDto.getMobile());

        //密码md5加密鉴权
        String md5 = SecureUtil.md5(userDto.getPassword());
        if (Objects.isNull(yddUser) || !md5.equals(yddUser.getPassword())) {
            //暂无该用户/密码错误,登录失败!
            throw new BusinessException(ErrorResult.loginError());
        }

        //登录成功,封装为json对象
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", yddUser.getId().toString());
        claims.put("mobile", yddUser.getMobile());
        String token = JwtUtils.getToken(claims);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);

        return R.success(map);
    }
}
